package com.linxianqin.restTemplate.controller;

import com.linxianqin.restTemplate.model.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * @author lxq
 * @version 1.0
 * @description: 通过 restTemplate exchange发送各种请求，可以解决delete和put没有返回值的问题
 * @date 2021/1/14 17:25
 */
@Slf4j
@RestController
public class ExchangeController {
    private RestTemplate restTemplate;
    public ExchangeController(RestTemplate restTemplate){
        this.restTemplate=restTemplate;
    }
    @GetMapping("exchange/put")
    public void put(){
        String url="http://localhost:8092/user/address";
        LoginParam loginParam = new LoginParam();
        loginParam.setUsername("admin");
        loginParam.setPassword("admin123");
        HttpEntity<LoginParam> request =  new HttpEntity<>(loginParam,null);
        //  执行HTTP请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, request, String.class);
        log.info("exchange/put:{}",responseEntity.getBody());
    }

    @GetMapping("exchange/delete")
    public void delete(){
        String url="http://localhost:8092/test/delete/{1}";
//        HashMap<String, Object> params = new HashMap<>();
//        params.put("username","admin");
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, null, String.class,1);
        log.info("exchange/delete,getBody:{}",responseEntity.getBody());
        log.info("exchange/delete,getStatusCode:{}",responseEntity.getStatusCode());
        log.info("exchange/delete,getHeaders:{}",responseEntity.getHeaders());
    }

    /**
     * 超时测试，restTemplate设置5秒。提供方休眠等待6秒，触发超时
     */
    @GetMapping("exchange/delete2")
    public void delete2(){
        String url="http://localhost:8092/test/delete2?name={name}";
        HashMap<String, Object> params = new HashMap<>();
        params.put("name","admin");
        try{
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, null, String.class,params);
            log.info("exchange/delete,getBody:{}",responseEntity.getBody());
            log.info("exchange/delete,getStatusCode:{}",responseEntity.getStatusCode());
            log.info("exchange/delete,getHeaders:{}",responseEntity.getHeaders());
        }catch (ResourceAccessException e) {
            log.info("超时了");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
